﻿using System;
using System.Collections.Generic;
using Citi.FinancePlanningAnalysis.SchedulerUi.SchedulerWcf;
using Citi.RoutineBase;

namespace Citi.FinancePlanningAnalysis.SchedulerUi
{
    public class CrcStartProcess : IExecutableRoutine
    {
        public new IEnumerable<RoutineParameter> Parameters
        {
            get
            {
                return new List<RoutineParameter> { 
                    new RoutineParameter{ Description = "If you want to start a routine when it's finished, insert the Routine Id.", 
                        Name ="SuccessorRoutineId", Nullable = true, Required = false, Type = typeof(int)}
                };
            }
        }

        public void Rollback(ref ICurrentAction currentAction, Dictionary<string, object> parameters)
        {
            
        }

        public void Start(DateTime scheduledDate, ref ICurrentAction currentAction, Dictionary<string, object> parameters)
        {
            var successorRoutineId = parameters.ContainsKey("SuccessorRoutineId") ? parameters["SuccessorRoutineId"].ToString() : null;

            if (!string.IsNullOrWhiteSpace(successorRoutineId))
                SetSucessorRoutine(int.Parse(successorRoutineId), currentAction);
        }

        private void SetSucessorRoutine(int successorRoutineId, ICurrentAction currentAction)
        {
            if (successorRoutineId <= 0) return;

            currentAction.Description = "Scheduling successor routine";

            using (var client = new ScheduleClient())
                client.ExecuteRoutineOnDemandById(successorRoutineId, null);

            currentAction.Description = "Successor routine scheduled. It will be executed as soon as possible";
        }

        public void Stop(ref ICurrentAction currentAction, Dictionary<string, object> parameters)
        {
            
        }
    }
}
